package com.hframe.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * 编号生成工具
 * 
 * @author heqian
 *
 */
public class NumberUtils {
	private static String B36[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
			"X", "Y", "Z" };

	public static String valToB36(long value, int lenght) throws Exception {
		if (value < 0)
			throw new Exception("数值不能为负数");

		if (lenght < 0)
			throw new Exception("输出升序不能负数");

		String ret = "";
		int len = B36.length;
		while (value > len) {
			ret = B36[(int) (value % len)] + ret;
			value /= len;
		}
		ret = "00000000000000000000" + B36[(int) value] + ret;
		return ret.substring(ret.length() - lenght);
	}

	private static int find(String b) throws Exception {
		for (int i = 0; i < B36.length; i++) {
			if (B36[i].equals(b))
				return i;
		}

		throw new Exception("错误数据格式");
	}

	public static long b36ToVal(String b36) throws Exception {
		long ret = 0;
		long s = 1;
		int len = B36.length;
		for (int i = len - 1; i >= 0; i--) {
			ret += find(b36.substring(i, i + 1)) * s;
			s *= 36;
		}
		return len;
	}

	/**
	 * 创建一个编号
	 * 
	 * @param type
	 *            类型
	 * @param date
	 *            日期
	 * @param number
	 *            序号
	 * @return 返回编号字符串
	 * @throws Exception
	 */
	public static String createNumber(int type, Date date, long number) throws Exception {
		String ret = valToB36(type, 1);
		Calendar cal = Calendar.getInstance();

		ret += ("" + cal.get(Calendar.YEAR)).substring(2);
		ret += valToB36(cal.get(Calendar.MONTH), 1);
		ret += valToB36(cal.get(Calendar.DATE), 1);
		ret += valToB36(number / 1000, 2);

		String temp = "000" + number % 1000;
		return ret + temp.substring(temp.length() - 3);
	}

}
